<template>
  <div class="category-container">
    <div class="toolbar">
      <el-button type="primary" @click="openDialog()">新增分类</el-button>
      <el-button @click="handleExpand">展开/折叠</el-button>
    </div>

    <el-table
        ref="tableRef"
        class="mt-4"
        size="large"
        v-loading="loading"
        :data="treeData"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        empty-text="暂无分类数据"
    >
      <el-table-column
          label="分类名称"
          prop="categoryName"
          min-width="200"
          show-overflow-tooltip
      />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" link @click="editAddDialog(row)">新增</el-button>
          <el-button size="small" type="primary" link @click="editDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" link @click="deleteCategory(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗表单 -->
    <el-dialog
        v-model="dialogVisible"
        :title="form.id ? '编辑分类' : '新增分类'"
        width="500px"
        align-center
    >
      <el-form :model="form" label-width="100px" class="form-body">
        <el-form-item label="分类名称">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" v-if="form.id">
          <el-tree-select
              v-model="form.id"
              :data="treeData"
              style="width: 100%"
              :props="{ label: 'categoryName', value: 'id', children: 'children' }"
              placeholder="请选择父级分类"
              clearable
              disabled
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessageBox, ElMessage } from 'element-plus'
import {delassetList, getassetList, inserAsset} from "../../apis/asset/index.js";

// 示例数据（你提供的结构）
const treeData = ref([])
const tableRef = ref(null)
const loading = ref(false)
let isExpand = true

const defaultProps = {
  children: 'children',
  label: 'categoryName'
}

onMounted(async () => {
  await getList()
})
const getList = async () => {
  loading.value = true
  try {
    const response = await getassetList()
    treeData.value = response
    // 默认展开所有行
    await nextTick()
    toggleExpand(treeData.value, true)
  } finally {
    loading.value = false
  }
}

const handleExpand = () => {
  isExpand = !isExpand
  toggleExpand(treeData.value, isExpand)
}

const toggleExpand = (children, unfold = true) => {
  for (const key in children) {
    tableRef.value?.toggleRowExpansion(children[key], unfold)
    if (children[key].children) {
      toggleExpand(children[key].children, unfold)
    }
  }
}
const dialogVisible = ref(false)
const form = ref({
  id: null,
  categoryName: '',
  parentId: 0,
  createTime: ''
})

const openDialog = (data = null) => {

    form.value = {
      id: null,
      categoryName: '',
      parentId: '',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    }
  dialogVisible.value = true
}
const editDialog = (data = null) => {
    form.value = { ...data }

  dialogVisible.value = true
}
const editAddDialog = (data = null) => {
  form.value = {
    id: data.id,
    categoryName: '',
    parentId: data.id,
    status:1
  }
  dialogVisible.value = true
}
const submitForm =  () => {
  console.log(JSON.stringify(form.value))
  if (form.value.id !== null) {
    // 编辑模式
    if(form.value.status){
      let np = {
        id: null,
        categoryName: form.value.categoryName,
        parentId: form.value.id
      }
      inserAsset(np).then(async () => {
        ElMessage.success('保存成功')
        await getList()
      })
    }else{
      inserAsset(form.value).then(async () => {
        ElMessage.success('保存成功')
        await getList()
      })
    }

  } else {
    // 新增模式
    const newNode = {
      categoryName: form.value.categoryName
    }
    inserAsset(newNode).then(async () => {
      ElMessage.success('添加成功')
      await getList()
    })
  }
  form.value = {
    id: null,
    categoryName: '',
    parentId: '',
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  dialogVisible.value = false
}



function deleteCategory(data) {
  ElMessageBox.confirm(`确定删除 "${data.categoryName}" 及其所有子分类吗？`, '警告', {
    type: 'warning'
  }).then(() => {
    delassetList({id:data.id}).then(async () => {
      ElMessage.success('删除成功')
      await getList()
    })
  })
}

function removeNode(nodes, id) {
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i].id === id) {
      nodes.splice(i, 1)
      return true
    }
    if (nodes[i].children) {
      if (removeNode(nodes[i].children, id)) return true
    }
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.toolbar {
  display: flex;
  justify-content: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.form-body {
  padding: 10px 10px 0;
}
</style>

